<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <title>设备联动</title>
    <link rel="stylesheet" href="../css/header.css">
    <link rel="stylesheet" href="../css/layout.css">
    <script type="text/javascript" src="../script/mqttws31.js"></script>
    <script type="text/javascript" src="../script/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="../script/jquery.md5.js"></script>
</head>
<body>
    <div class="wrapper wuhuakongzhiqi">
        <header id="header" class="header">
            <div class="head">
                <!-- <a class="left" onclick="checkpage()" id="backleft"></a> -->
                <span class="center" id="device_name">雾化控制器</span>
                <!-- <a class="right" onclick="setting()" id="backright"></a> -->
            </div>
        </header>
    	<div class="content">
    		<table border="1">
    		  <tr>
    		    <th>ID</th>
    		    <th>Name</th>
    		    <th>压力值</th>
    		    <th>运行状态</th>
    		    <th>设备通讯状态</th>
    		    <th>时间</th>
    		    <th>模式</th>
    		    <th>开关</th>
    		    <th>设置</th>
    		  </tr>
    		  <!-- <tr>
    		    <td>10000</td>
    		    <td>MiCO-3165</td>
    		    <td>40</td>
    		    <td>ON</td>
    		    <td>正常</td>
    		    <td>13:53:24</td>
    		    <td>自动连续</td>
    		    <td><button onclick="devopenclose()">按钮</button></td>
    			<td><button onclick="devsetting()">设置</button></td>
    		  </tr> -->
    		</table>
    	</div>
    </div>
</body>
	<script>
        // var systimerecv;     //系统时间

        // var lighttimerecv;     //背光时间

        // var lightlevelrecv;     //灯光亮度

        // var ctlmoderecv;     //控制方式

        // //var inputiorecv;     //输入端口
        // var input0recv;
        // var input1recv;
        // var input2recv;
        // var input3recv;
        // var ain0recv;
        // var ain1recv;
        // var ain3recv;

        // //var outputiorecv;     //输出端口
        // var pout0recv;
        // var pout1recv;
        // var out0recv;
        // var out1recv;
        // var out2recv;
        // var out3recv;
        // var out4recv;

        // var fengintmoderecv;     //风间隙模式
        // var wuintmoderecv;     //雾间隙模式

        // var openinttimerecv;     //间隙开时间
        // var closeinttimerecv;     //间隙关时间

        // var fengtimswitchrecv;     //风定时
        // var wutimswitchrecv;     //雾定时
        // var dengtimswitchrecv;     //灯定时

        // var timtime_fengkairecv;     //风定时开
        // var timtime_fengguanrecv;     //风定时关
        // var timtime_wukairecv;     //雾定时开
        // var timtime_wuguanrecv;     //雾定时关
        // var timtime_dengkairecv;     //灯定时开
        // var timtime_dengguanrecv;     //灯定时关

        // var funcselswitchrecv;     //功能开关

        // var shangxianpressrecv;     //压力上限
        // var xiaxianpressrecv;     //压力下限
        // var shedingpressrecv;     //压力设定
        // var liangchengpressrecv;     //压力量程

        var idarray = new Array();
        var namearray = new Array();
        var onlinearray = new Array();
        
        //配置签名
        var app_secret = '9b253c408551c9a7d9b719853462d510';
        var timestamp = new Date().getTime();
        var signString = $.md5(app_secret+timestamp)+', '+timestamp;
        //获取设备列表
        $.ajax({
            type : 'post',
            url : 'http://api.easylink.io/v1/device/fetchByPage',
            headers : {
                "Authorization" : "token a1863b45-d3f3-454d-b951-ab58adfc7ec8",
                "X-Application-Id" : 'cc855e1a-f0f6-43c8-aeda-914b1f054e92',
                //"X-Request-Sign" : signString
            },
            data : {
                'limit' : 10
            },
            success : function(data) {
                $(data.data).each(function(n,element){
                    idarray.push(element.id);
                    namearray.push(element.alias);
                    onlinearray.push(element.online)
                });
                var statustab = $("table>tbody").html();        
                // 如果设备ID不为空，则执行连接MQTT的操作
                if (idarray.length !== 0) {
                    $(idarray).each(function(n,element){
                        ez_connect(element,n);//连接每一个设备
                        var onlinetxt;
                        if(onlinearray[n] == 0){
                            onlinetxt = "offline";
                        }else{
                            onlinetxt = "online";
                        }
                        statustab += '<tr>'
                            + '<td>' + element + '</td>'
                            + '<td>' + namearray[n] + '</td>'
                            + '<td>0</td>'
                            + '<td>未连</td>'
                            + '<td>'+onlinetxt+'</td>'
                            + '<td>00:00:00</td>'
                            + '<td></td>'
                            + '<td><button onclick="devopenclose(\'' + element + '\',\'' + n + '\')">开机</button></td>'
                            + '<td><button onclick="devsetting(\'' + element + '\',\'' + n + '\')">设置</button></td>'
                            + '</tr>';
                    });
                }
                $("table>tbody").html(statustab);

                console.log("success" + data);
            },
            error : function(data) {
                console.log("失败了" + data.responseText);
            }
        });

        var clientArray = new Array();     
        // 连接MQTT服务
        function ez_connect(device_id,n) {
            var host = "api.easylink.io";
            var port = 1983;
            //clientID，需要按照此标准来定义：v1-app-[MAC]  版本号-app-手机MAC(12位)
            var clientID = "v1-app-" + parseInt(Math.random() * (1000000000000), 12);
            var client = new Paho.MQTT.Client(host, Number(port), clientID);
            client.onConnectionLost = onConnectionLost;
            client.onMessageArrived = onMessageArrived;
            client.connect({onSuccess:onConnect});
            clientArray.push(client);
            function onConnect() {
                // Once a connection has been made, make a subscription and send a message.
                console.log("onConnect");
                client.subscribe(device_id + "/out");   //订阅消息
                //message = new Paho.MQTT.Message(device_id);
                //message.destinationName = "/World";
                //client.send(message);     //发送消息
            };
            function onConnectionLost(responseObject,n) {
                //###加上网页断线的提示
                //$("table>tbody>tr").eq(Math.floor(n)+1).children().eq(4).text("故障");//名称
                if (responseObject.errorCode !== 0)
                    console.log("onConnectionLost:"+responseObject.errorMessage);   //连接断开
            };
            function onMessageArrived(message) {
                // console.log("onMessageArrived:"+message.payloadString);   //显示发来的消息
                recvmsg(message);
                //client.disconnect(); 
            };
            //接收消息并处理
            function recvmsg(message) {
                //console.log("onMessageArrived:"+message.payloadString);   //显示发来的消息
                var ret = message.payloadString;
                var msgjson = JSON.parse(ret);
                $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(1).text(namearray[n]);//名称
                $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(2).text(msgjson.dev_pressval/10);//压力值
                //设备状态：dev_status 0 停止 1运行 2缺水故障 3欠压故障
                var dev_status_txt;
                switch(msgjson.dev_status){
                    case 0:dev_status_txt = "停止";
                        $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(7).children().text("开机");
                        break;
                    case 1:dev_status_txt = "运行";
                        $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(7).children().text("关机");
                        break;
                    case 2:dev_status_txt = "缺水故障";
                        $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(7).children().text("故障");
                        break;
                    case 3:dev_status_txt = "欠压故障";
                        $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(7).children().text("故障");
                        break;
                    default :break;
                }
                $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(3).text(dev_status_txt);
                // 
                //设备时间：dev_time 如：143100表示14：31：00
                var devtime = msgjson.dev_time;             //设备时间
                var devtimeshi = Math.floor(devtime/10000);//msgjson.dev_time_shi;      
                var devtimefen = Math.floor(devtime%10000/100);//msgjson.dev_time_fen;
                var devtimemiao = Math.floor(devtime%100);//msgjson.dev_time_miao;
                $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(5).text(devtimeshi+":"+devtimefen+":"+devtimemiao);//时间
                //设备模式   dev_mode   0自动连续 1自动间隙 2手动连续 3手动间隙
                var devmode;
                var ctlmoderecv = msgjson.ctlmode;//控制方式
                var fengintmoderecv = msgjson.fengintmode;
                var wuintmoderecv = msgjson.wuintmode;
                if(ctlmoderecv == 1){
                    if(fengintmoderecv || wuintmoderecv){
                        devmode = 3;//手动间隙
                    }else{
                        devmode = 2;//手动连续
                    }
                }else{
                    if(fengintmoderecv || wuintmoderecv){
                        devmode = 1;//自动间隙
                    }else{
                        devmode = 0;//自动连续
                    }
                }
                switch(devmode){
                    case 0: $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(6).text("自动连续"); break;
                    case 1: $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(6).text("自动间隙"); break;
                    case 2: $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(6).text("手动连续"); break;
                    case 3: $("table>tbody>tr").eq(Math.floor(n)+1).children().eq(6).text("手动间隙"); break;
                    default: break;
                }
            };
        }

        //发送指令
        function publishcmd(topic, command) {   //publishcmd("60b3105c/d0bae401bd98" + "/out",'{"dev_status":false}')
            //var topic = "60b3105c/d0bae401bd98" + '/out';   //60b3105c/d0bae401bd98/out
            message = new Paho.MQTT.Message(command);
            message.destinationName = topic;
            var clientindex = idarray.indexOf(topic.substring(0,21));
            clientArray[clientindex].send(message);     //发送消息
        };
        
        //设备开关
        function devopenclose(id,n){
            var topic = id + '/in';
            var command;
            if($("table>tbody>tr").eq(Math.floor(n)+1).children().eq(3).text() == "运行"){
                command = '{"devstatus":false}';     //开关命令
                //$("table>tbody>tr").eq(Math.floor(n)+1).children().eq(3).text("ON");
            }else{
                command = '{"devstatus":true}';     //开关命令
                //$("table>tbody>tr").eq(Math.floor(n)+1).children().eq(3).text("OFF");
            }
            publishcmd(topic, command);
        }
        //设置
        function devsetting(id,n){
            if($("table>tbody>tr").eq(Math.floor(n)+1).children().eq(3).text() == "停止")
                window.location.href = "./wuhuakongzhiqi.html?id="+id;
        }


//         //      返回上一页
//         function checkpage() {
//             api.closeWin();
//             //关闭mqtt，关闭的时候需要同事关闭消息接收和MQTT连接
//             micoMqtt.stopRecvMqttMsg(function(ret, err) {
//             });
//             micoMqtt.stopMqtt(function(ret, err) {
//             });
//             window.location.href = "./devlist.html";
//         };
//         // function setting(){
//         //     window.location.href = "./wuhuakongzhiqi.html";
//         // }
//         // 跳转到控制设备的页面，如果设备离线则不让跳转
//         function setting() {
//             //api.closeWin();
//             if(settingctrl){
//                 api.openWin({
//                 name : 'wuhuakongzhiqi',
//                 url : './wuhuakongzhiqi.html',
//                 slidBackEnabled : false,
//                 reload : true,
//                 bgColor : '#F0F0F0',
//                 animation : {
//                     type : 'none'
//                 },
//                 pageParam : {
//                     "deviceid" : device_id,
//                     "devicename" : device_name,
//                     "systimerecv" : systimerecv,
//                     "lighttimerecv" : lighttimerecv,

//                     "systimerecv" : systimerecv,         //系统时间

//                     "lighttimerecv" : lighttimerecv,         //背光时间

//                     "lightlevelrecv" : lightlevelrecv,         //灯光亮度

//                     "ctlmoderecv" : ctlmoderecv,         //控制方式

//                     // "inputiorecv" : inputiorecv,         //输入端口
//                     // "outputiorecv" : outputiorecv,         //输出端口
                    
//                     "input0recv" : input0recv,
//                     "input1recv" : input1recv,
//                     "input2recv" : input2recv,
//                     "input3recv" : input3recv,
//                     "ain0recv" : ain0recv,
//                     "ain1recv" : ain1recv,
//                     "ain3recv" : ain3recv,


//                     "pout0recv" : pout0recv,
//                     "pout1recv" : pout1recv,
//                     "out0recv" : out0recv,
//                     "out1recv" : out1recv,
//                     "out2recv" : out2recv,
//                     "out3recv" : out3recv,
//                     "out4recv" : out4recv,


//                     "fengintmoderecv" : fengintmoderecv,         //风间隙模式
//                     "wuintmoderecv" : wuintmoderecv,         //雾间隙模式

//                     "openinttimerecv" : openinttimerecv,         //间隙开时间
//                     "closeinttimerecv" : closeinttimerecv,         //间隙关时间

//                     "fengtimswitchrecv" : fengtimswitchrecv,         //风定时
//                     "wutimswitchrecv" : wutimswitchrecv,         //雾定时
//                     "dengtimswitchrecv" : dengtimswitchrecv,         //灯定时

//                     "timtime_fengkairecv" : timtime_fengkairecv,         //风定时开
//                     "timtime_fengguanrecv" : timtime_fengguanrecv,         //风定时关
//                     "timtime_wukairecv" : timtime_wukairecv,         //雾定时开
//                     "timtime_wuguanrecv" : timtime_wuguanrecv,         //雾定时关
//                     "timtime_dengkairecv" : timtime_dengkairecv,         //灯定时开
//                     "timtime_dengguanrecv" : timtime_dengguanrecv,         //灯定时关

//                     "funcselswitchrecv" : funcselswitchrecv,         //功能开关

//                     "shangxianpressrecv" : shangxianpressrecv,         //压力上限
//                     "xiaxianpressrecv" : xiaxianpressrecv,         //压力下限
//                     "shedingpressrecv" : shedingpressrecv,         //压力设定
//                     "liangchengpressrecv" : liangchengpressrecv         //压力量程
//                 }
//             });
//             }else{
//                 return;
//             }
            
            
//         }
    </script>
</html>